/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.shortlink.utils;


import com.alibaba.ttl.TransmittableThreadLocal;
import com.shortlink.pojos.dto.dataobject.UserInfoDO;

import java.util.Optional;

/**
 * 用户上下文
 */
public final class UserContext {

    /**
     * <a href="https://github.com/alibaba/transmittable-thread-local" />
     */
    private static final ThreadLocal<UserInfoDO> USER_THREAD_LOCAL = new TransmittableThreadLocal<>();

    /**
     * 设置用户至上下文
     *
     * @param user 用户详情信息
     */
    public static void setUser(UserInfoDO user) {
        USER_THREAD_LOCAL.set(user);
    }

    public static UserInfoDO getUser(){
        return Optional.ofNullable(USER_THREAD_LOCAL.get()).orElse(null);
    }

    /**
     * 获取上下文中用户 ID
     *
     * @return 用户 ID
     */
    public static Long getUserId() {
        UserInfoDO userInfoDO = USER_THREAD_LOCAL.get();
        return Optional.ofNullable(userInfoDO).map(UserInfoDO::getId).orElse(null);
    }

    /**
     * 获取上下文中用户名称
     *
     * @return 用户名称
     */
    public static String getUsername() {
        UserInfoDO userInfoDO = USER_THREAD_LOCAL.get();
        return Optional.ofNullable(userInfoDO).map(UserInfoDO::getUsername).orElse(null);
    }

    /**
     * 清理用户上下文
     */
    public static void removeUser() {
        USER_THREAD_LOCAL.remove();
    }
}